import random

from django.http import HttpResponse
from django.shortcuts import render, redirect,get_object_or_404
from django.contrib import messages
from rest_framework.views import APIView
# Create your views here.
from rest_framework import viewsets
from .models import Productcomment,Kind
from utils.serializers import ProductSerializer
from .models import Products
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.core.serializers import serialize
import json
from django import forms
from users.models import Users


class ProductViewSet(viewsets.ModelViewSet):
    serializer_class = ProductSerializer
    #示例
    # def create(self, request, *args, **kwargs):
    #     serializer = self.get_serializer(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     self.perform_create(serializer)
    #     headers = self.get_success_headers(serializer.data)
    #     return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
    def get_queryset(self):
        queryset = Products.objects.all()
        # 获取请求参数
        name = self.request.query_params.get('name')
        category = self.request.query_params.get('category')
        price_min = self.request.query_params.get('price_min')
        price_max = self.request.query_params.get('price_max')

        # 根据请求参数进行条件筛选
        if name:
            queryset = queryset.filter(pname__icontains=name)
        if category:
            queryset = queryset.filter(kindid=category)
        if price_min:
            queryset = queryset.filter(price__gte=price_min)
        if price_max:
            queryset = queryset.filter(price__lte=price_max)

        return queryset

        # 准备传递给模板的数据

class search(APIView):
    def get(self, request):
        keyword = request.GET.get('keyword', '').lower()
        queryset = Products.objects.all()
        if keyword:
            queryset = queryset.filter(pname__icontains=keyword)
        products = []
        for product in queryset:
            products.append({
                'productid': product.productid,
                'pname': product.pname,
                'price': product.price,
                # 添加其他需要展示的字段
            })

        # 渲染模板，并传递数据
        return render(request, 'search.html', {'products': products})




#AddProductView实现添加商品信息
class ProductForm(forms.ModelForm):
    class Meta:
        model = Products
        fields = ['productid', 'pname', 'price', 'inventory']
        widgets = {
            'productid': forms.TextInput(attrs={'class': 'form-control'}),
            'pname': forms.TextInput(attrs={'class': 'form-control'}),
            'price': forms.NumberInput(attrs={'class': 'form-control'}),
            'inventory': forms.NumberInput(attrs={'class': 'form-control'}),
        }
class AddProductView(APIView):
    def get(self, request):
        form = ProductForm()
        return render(request, 'add_product.html', {'form': form})
    def post(self, request):
        form = ProductForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, '商品添加成功！')
            return redirect('/add_product')
        else:
            for field, error in form.errors.items():
                messages.error(request, f"{field}: {error}")
        return render(request, 'add_product.html', {'form': form})
class Detail(APIView):
    def get(self, request):
            request.session['productid'] = '1    '
            return render(request, 'detail.html')

class CommentProfileForm(forms.Form):
    productid =forms.CharField(required=False, label='商品ID')
    comment = forms.CharField(required=False, label='评论')


class Comment(APIView):
    def get(self, request):
        form = CommentProfileForm()
        return render(request, 'comment.html', {'form': form})


    def post(self, request):
        form = CommentProfileForm(request.POST)
        if form.is_valid():
            product_id = form.cleaned_data['productid']
            comment_text = form.cleaned_data['comment']
            action = request.POST.get('action')

            if action == '1':
                product_instance = Products.objects.get(productid=product_id)
                new_comment = Productcomment.objects.create(
                    commentid=random.randint(1000, 9999),
                    productid=product_instance,
                    comment=comment_text,
                )
                return HttpResponse("新增评论成功")
            elif action == '2':
                try:
                    Productcomment.objects.filter(productid=product_id ,comment=comment_text).delete()
                    messages.success(request, "评论删除成功")
                    return redirect('/comment/')
                except Exception as e:
                    return HttpResponse("删除失败：" + str(e), status=400)
            elif action == '3':
                try:
                    comment = Productcomment.objects.get(productid=product_id)
                    comment.comment = comment_text
                    comment.save()
                    return HttpResponse("评论修改成功")
                except Productcomment.DoesNotExist:
                    return HttpResponse("评论不存在", status=404)
            elif action == '4':
                if product_id:
                    comments = Productcomment.objects.filter(productid=product_id)
                    return render(request, 'comment.html', {'comments': comments, 'form': form})
            else:
                return HttpResponse("未知操作", status=400)
        else:
            messages.error(request, "表单数据有误，请检查后重新提交")
            return render(request, 'comment.html', {'form': form})
        



class KindProfileForm(forms.Form):
    userid = forms.CharField(required=False, label='留言人')
    kdescription = forms.CharField(required=False, label='留言')



class Kinds(APIView):
    def get(self, request):
        use_id = request.session.get('username')
        if use_id:
            form = KindProfileForm(initial={'userid': use_id})
            kdescription = Users.objects.filter(userid=use_id)
            return render(request, 'message.html', {'form': form, 'kdescription': kdescription})
        else:
            return HttpResponse(use_id)

    def post(self, request):
        form = KindProfileForm(request.POST)
        if form.is_valid():
            use_id = form.cleaned_data['userid']
            message_text = form.cleaned_data['kdescription']
            action = request.POST.get('action')

            if action == '1':
                new_message = Kind.objects.create(
                    messageid=random.randint(1000, 9999),
                    userid=use_id,
                    message=message_text,
                )
                return HttpResponse("新增留言成功")
            elif action == '2':
                try:
                    Kind.objects.filter(userid=use_id).delete()
                    messages.success(request, "评论删除成功")
                    return redirect('/message/')
                except Exception as e:
                    return HttpResponse("删除失败：" + str(e), status=400)
            elif action == '3':
                try:
                    kdescription = Kind.objects.get(userid=use_id)
                    kdescription.message = message_text
                    kdescription.save()
                    return HttpResponse("留言修改成功")
                except Kind.DoesNotExist:
                    return HttpResponse("留言不存在", status=404)
            elif action == '4':
                if use_id:
                    kdescription = Kind.objects.filter()
                    return render(request, 'message.html', {'form': form, 'kdescription': kdescription})
            else:
                return HttpResponse("未知操作", status=400)
        else:
            messages.error(request, "表单数据有误，请检查后重新提交")
            return render(request, 'message.html', {'form': form})